// cloudfunctions/getCart/index.js
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

exports.main = async (event, context) => {
  const { userId } = event

  if (!userId) {
    return {
      success: false,
      message: '用户ID缺失'
    }
  }

  try {
    // 获取购物车商品
    const cartRes = await db.collection('carts').where({
      userId: userId
    }).get()

    const cartItems = cartRes.data

    // 获取对应的商品信息
    const productIds = cartItems.map(item => item.productId)
    const productsRes = await db.collection('products').where({
      _id: db.command.in(productIds)
    }).get()

    const products = productsRes.data

    // 组合购物车项和商品信息
    const items = cartItems.map(item => {
      const product = products.find(p => p._id === item.productId)
      return {
        ...item,
        product: product
      }
    })

    return {
      success: true,
      data: items
    }

  } catch (err) {
    return {
      success: false,
      message: '获取购物车失败',
      error: err
    }
  }
}
